package com.cxz.food.controller;

import com.cxz.food.domain.Business;
import com.cxz.food.exception.CustomException;
import com.cxz.food.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private BusinessService businessService;


    @RequestMapping(value = "/login")
    public String login(){

        return "login";
    }


    @RequestMapping(value = "/loginSubmit")
    public String loginSubmit(HttpServletRequest request ,@RequestParam String username, String password){

        Business business = businessService.getBusinessByName(username);

        if(business==null){
            request.setAttribute("error","没有该用户");
            return "forward:login" ;
        }else {

            if(!business.getPassword().equals(password)){
                request.setAttribute("error","用户名密码错误");
                return "redirect:login" ;
            }

            Integer id = business.getId();
            HttpSession session = request.getSession();

            session.setAttribute("businessId",id);

            session.setAttribute("businessName",business.getBusinessname());

            return "redirect:/food/getFoodList" ;
        }
    }


    @RequestMapping(value = "/register")
    public String register(){

        return "register";
    }


    @RequestMapping(value = "/registerSubmit",method = RequestMethod.POST,produces = "application/json")
    public String registerSubmit(Business business){


        businessService.addBusiness(business);


        return "redirect:/user/login";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){

        session.removeAttribute("businessId");

        return "redirect:/user/login";
    }

}
